package com.glodon.ggzy.fwpt.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.glodon.ggzy.core.model.Page;
import com.glodon.ggzy.core.utils.PageSearchModel;
import com.glodon.ggzy.core.utils.QuerySupport;
import com.glodon.ggzy.entity.GgJsLaw;
import com.glodon.ggzy.entity.GgJsProjectInfo;
import com.glodon.ggzy.entity.GgJsSchedule;
import com.glodon.ggzy.entity.GgJsTenderNotice;
import com.glodon.ggzy.entity.GgJsWinningPublic;
import com.glodon.ggzy.fwpt.dao.IGgJsLawDao;
import com.glodon.ggzy.fwpt.dao.IGgJsProjectInfoDao;
import com.glodon.ggzy.fwpt.dao.IGgJsScheduleDao;
import com.glodon.ggzy.fwpt.dao.IGgJsTenderNoticeDao;
import com.glodon.ggzy.fwpt.dao.IGgJsWinningPublicDao;
import com.glodon.ggzy.fwpt.service.IJsgcProjectService;
import com.glodon.ggzy.vo.JgptJsgc;
import com.glodon.ggzy.vo.JgptJsgcBean;
import com.glodon.ggzy.vo.JgptJsgcDetail;

/**
 * 
 * 建设工程处理Service实现类
 * @author yangjf
 * @date 2013/06/11
 */
@Service
public class JsgcProjectServiceImpl implements IJsgcProjectService {

	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private IGgJsProjectInfoDao projectInfoDao;

	@Autowired
	private IGgJsTenderNoticeDao tenderNoticeDao;

	@Autowired
	private IGgJsWinningPublicDao winningPublicDao;

	@Autowired
	private IGgJsLawDao lawDao;

	@Autowired
	private IGgJsScheduleDao scheduleDao;

	@Override
	public Page queryJsgcProjectInfo(PageSearchModel queryModel, String projectName) {
		queryModel.addParamToMap(QuerySupport.QUERYCLASS, GgJsProjectInfo.class);
		if (!StringUtils.isEmpty(projectName)) {
			queryModel.addParamToMap("projectName_like", "%" + projectName + "%");
		}
		queryModel.addParamToMap(QuerySupport.ORDERBYDESC, "to_number(id)");
		return projectInfoDao.pageQuery(queryModel.getParamsMap(), queryModel.getPageNo(), queryModel.getPageSize());
	}

	@Override
	public GgJsProjectInfo getGgJsProjectInfoById(String id) {
		return projectInfoDao.get(id);
	}

	@Override
	public GgJsTenderNotice getGgJsTenderNoticeByProjId(String projectId) {
		try {
			GgJsTenderNotice tenderNotice = null;
			List<GgJsTenderNotice> list = new ArrayList<GgJsTenderNotice>();
			DetachedCriteria criteria = DetachedCriteria.forClass(GgJsTenderNotice.class);
			criteria.add(Restrictions.eq("projectId", projectId));
			list = tenderNoticeDao.findByDetachedCriteria(criteria);
			if (list != null && list.size() > 0) {
				tenderNotice = list.get(0);
			}
			return tenderNotice;
		} catch (Exception ex) {
			logger.error("获取数据失败！", ex);
			return null;
		}
	}

	@Override
	public GgJsTenderNotice getGgJsTenderNoticeByIdAndType(String projectId, String noticeType) {
		try {
			GgJsTenderNotice tenderNotice = null;
			List<GgJsTenderNotice> list = new ArrayList<GgJsTenderNotice>();
			DetachedCriteria criteria = DetachedCriteria.forClass(GgJsTenderNotice.class);
			criteria.add(Restrictions.eq("projectId", projectId));
			criteria.add(Restrictions.eq("noticeType", noticeType));
			list = tenderNoticeDao.findByDetachedCriteria(criteria);
			if (list != null && list.size() > 0) {
				tenderNotice = list.get(0);
			}
			return tenderNotice;
		} catch (Exception ex) {
			logger.error("获取数据失败！", ex);
			return null;
		}
	}

	@Override
	public GgJsWinningPublic getGgJsWinningPublicByProjId(String projectId) {
		try {
			GgJsWinningPublic winningPublic = null;
			List<GgJsWinningPublic> list = new ArrayList<GgJsWinningPublic>();
			DetachedCriteria criteria = DetachedCriteria.forClass(GgJsWinningPublic.class);
			criteria.add(Restrictions.eq("projectId", projectId));
			list = winningPublicDao.findByDetachedCriteria(criteria);
			if (list != null && list.size() > 0) {
				winningPublic = list.get(0);
			}
			return winningPublic;
		} catch (Exception ex) {
			logger.error("获取数据失败！", ex);
			return null;
		}
	}

	@Override
	public GgJsTenderNotice getGgJsTenderNoticeById(String id) {
		return tenderNoticeDao.get(id);
	}

	@Override
	public Page queryJsgcTenderNotice(PageSearchModel queryModel, String noticeName) {
		queryModel.addParamToMap(QuerySupport.QUERYCLASS, GgJsTenderNotice.class);
		if (!StringUtils.isEmpty(noticeName)) {
			queryModel.addParamToMap("noticeName_like", "%" + noticeName + "%");
		}
		queryModel.addParamToMap(QuerySupport.BLOCK, "(noticeType = 'zbgg' or noticeType = 'fjczbgg')");
		return tenderNoticeDao.pageQuery(queryModel.getParamsMap(), queryModel.getPageNo(), queryModel.getPageSize());
	}

	@Override
	public Page queryJsgcWinningPublic(PageSearchModel queryModel, String projectName) {
		StringBuffer hql = new StringBuffer();
		StringBuffer countHql = new StringBuffer();
		Map<String, Object> parameterMap = new HashMap<String, Object>();
		hql.append("select project,winning from GgJsProjectInfo project , GgJsWinningPublic winning where project.id = winning.projectId ");
		countHql.append("select count(*) from GgJsProjectInfo project , GgJsWinningPublic winning where project.id = winning.projectId ");
		if (!StringUtils.isEmpty(projectName)) {
			hql.append(" and project.projectName like:projectName");
			countHql.append(" and project.projectName like:projectName");
			parameterMap.put("projectName", "%" + projectName + "%");
		}
		return projectInfoDao.pageQuery(hql.toString(), parameterMap, countHql.toString(), queryModel.getPageNo(), queryModel.getPageSize());
	}

	@Override
	public GgJsWinningPublic getGgJsWinningPublicById(String id) {
		return winningPublicDao.get(id);
	}

	@Override
	public Page queryGgJsLaw(PageSearchModel queryModel, String lawName) {
		queryModel.addParamToMap(QuerySupport.QUERYCLASS, GgJsLaw.class);
		queryModel.addParamToMap(QuerySupport.ORDERBYDESC, "updatetime");
		if (!StringUtils.isEmpty(lawName)) {
			queryModel.addParamToMap("name_like", "%" + lawName + "%");
		}
		return lawDao.pageQuery(queryModel.getParamsMap(), queryModel.getPageNo(), queryModel.getPageSize());

	}

	@Override
	public GgJsLaw getGgJsLawById(String id) {
		return lawDao.get(id);
	}

	@Override
	public Page queryJsgcXzclInfo(PageSearchModel queryModel, String noticeName) {
		queryModel.addParamToMap(QuerySupport.QUERYCLASS, GgJsTenderNotice.class);
		queryModel.addParamToMap("noticeType", "tscljd");
		if (!StringUtils.isEmpty(noticeName)) {
			queryModel.addParamToMap("noticeName_like", "%" + noticeName + "%");
		}
		return tenderNoticeDao.pageQuery(queryModel.getParamsMap(), queryModel.getPageNo(), queryModel.getPageSize());
	}

	@Override
	public List<GgJsSchedule> queryJsgcScheduleInfo(String prjId) {
		if (StringUtils.isNotEmpty(prjId)) {
			return scheduleDao.findBy("projectId", prjId);
		} else {
			return null;
		}

	}

	@Override
	public List<JgptJsgcDetail> getJgptJsgcData(Date begin, Date end) {
		String hql = "select new com.glodon.ggzy.vo.JgptJsgc(to_char(w.publicStartTime,'yyyy-mm'),count(p.id),nvl(sum(p.budgetPrice),0))"
				+ " from GgJsWinningPublic w, GgJsProjectInfo p where w.projectId = p.id and w.publicStartTime between  ? and ?"
				+ " group by to_char(w.publicStartTime,'yyyy-mm') order by to_char(w.publicStartTime,'yyyy-mm')";
		List<JgptJsgc> jsgcList = projectInfoDao.find(hql, begin, end);
		List<JgptJsgcDetail> detailList = new ArrayList<JgptJsgcDetail>();
		if (jsgcList != null && jsgcList.size() > 0) {
			for (JgptJsgc jsgc : jsgcList) {
				JgptJsgcDetail detail = new JgptJsgcDetail();
				detail.setDate(jsgc.getDate());
				detail.setNums(jsgc.getNums());
				detail.setPrices(jsgc.getPrices());
				JgptJsgcBean sg = getJgptJsgcStat(jsgc.getPrices(), begin, end, "施工");
				detail.setSggs(sg.getNumber());
				detail.setSgjezb(sg.getAmount());
				detail.setSgysj(sg.getPrices());
				JgptJsgcBean jl = getJgptJsgcStat(jsgc.getPrices(), begin, end, "监理");
				detail.setJlgs(jl.getNumber());
				detail.setJljezb(jl.getAmount());
				detail.setJlysj(jl.getPrices());
				JgptJsgcBean kc = getJgptJsgcStat(jsgc.getPrices(), begin, end, "勘察");
				detail.setKcgs(kc.getNumber());
				detail.setKcjezb(kc.getAmount());
				detail.setKcysj(kc.getPrices());
				JgptJsgcBean sj = getJgptJsgcStat(jsgc.getPrices(), begin, end, "设计");
				detail.setSjgs(sj.getNumber());
				detail.setSjjezb(sj.getAmount());
				detail.setSjysj(sj.getPrices());
				detailList.add(detail);
			}
		}

		return detailList;
	}

	private JgptJsgcBean getJgptJsgcStat(double totalPrices, Date begin, Date end, String bidClasses) {
		JgptJsgcBean jsgcBean = new JgptJsgcBean();
		String hql = "select new com.glodon.ggzy.vo.JgptJsgcBean(count(p.id),nvl(sum(p.budgetPrice),0),nvl(sum(p.budgetPrice),0))"
				+ " from GgJsWinningPublic w, GgJsProjectInfo p where w.projectId = p.id and w.publicStartTime between  ? and ? and p.bidClasses =? "
				+ " group by to_char(w.publicStartTime,'yyyy-mm') order by to_char(w.publicStartTime,'yyyy-mm')";
		List<JgptJsgcBean> jsgcList = projectInfoDao.find(hql, begin, end, bidClasses);
		if (jsgcList != null && jsgcList.size() > 0) {
			jsgcBean = jsgcList.get(0);
			if (jsgcBean.getPrices() != 0) {
				jsgcBean.setAmount(jsgcBean.getPrices() / totalPrices);
				jsgcBean.setPrices(jsgcBean.getPrices() / 1000);
			}
		}
		return jsgcBean;
	}

	@Override
	public String getProjectTypeByCode(String code) {
		String projectType = "";
		if ("1".equals(code)) {
			projectType = "小额网上交易";
		} else if ("2".equals(code)) {
			projectType = "大额电子辅助评标";
		} else {
			projectType = "现场交易";
		}
		return projectType;
	}

	@Override
	public String getJointBiddingByCode(String code) {
		String joint = "";
		if ("false".equals(code)) {
			joint = "否";
		}
		if ("true".equals(code)) {
			joint = "是";
		}
		return joint;
	}

}
